package com.thinkgem.jeesite.common.utils;

import com.thinkgem.jeesite.modules.file.entity.FTPBean;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * ftp 文件上传、下载、显示工具类
 *
 * @author yangrui
 */
public class FTPUtils {

    private static Logger logger = Logger.getLogger(FTPUtils.class);

    private static final List<String> imgSuffixlist = new ArrayList<String>();

    static {
        imgSuffixlist.add("jpg");
        imgSuffixlist.add("jpeg");
        imgSuffixlist.add("bmp");
        imgSuffixlist.add("png");
        imgSuffixlist.add("gif");
    }

    /**
     * 文件上传
     * @param bean
     * @param in
     * @return
     */
    public static boolean uploadFile(FTPBean bean, InputStream in) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(bean.getHost(), bean.getPort());// 连接FTP服务器
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            boolean login = ftp.login(bean.getLoginName(), bean.getPassword());// 登录
            if (!login) {
                logger.debug("----->>>ftp服务器认证失败！");
                return success;
            }
            // 设置以二进制方式传输
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                logger.debug("----------->>>连接ftp服务器失败");
                return success;
            }
            if (!ftp.changeWorkingDirectory(bean.getStorePath())) {
                if (!CreateDirecroty(ftp, bean.getStorePath())) {
                    logger.info("----->>>创建目录失败……");
                    return success;
                }
            }
            ftp.enterLocalPassiveMode();
            boolean storeFile = ftp.storeFile(bean.getFtpFileName(), in);
            System.out.println(storeFile);
            if (!storeFile) {
                logger.debug("----->>>上传文件失败！");
                return success;
            }
            in.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            logger.error("----->>>异常" + e.getMessage());
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
        return success;
    }

    /**
     * 文件下载
     * @param bean
     * @param response
     * @return
     */
    public static boolean downFile(FTPBean bean, HttpServletResponse response) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(bean.getHost(), bean.getPort());
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(bean.getLoginName(), bean.getPassword());// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            //被动模式
          ftp.enterLocalPassiveMode();
            //主动模式
//            ftp.enterLocalActiveMode();
          ftp.changeWorkingDirectory(bean.getStorePath());// 转移到FTP服务器目录
            FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
            	System.out.println(ff.getName());
                if (ff.getName().equals(bean.getFtpFileName())) {
                    String fileName = bean.getOriginalFileName() != null ? bean.getOriginalFileName() : ff.getName();
                    String saveAsFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
                    response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName);
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                    OutputStream os = response.getOutputStream();
                    ftp.retrieveFile(ff.getName(), os);
                    os.flush();
                    os.close();
                    break;
                }
            }
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

        }
        return success;
    }

    /**
     * 图片回显
     * @param ftpBean
     * @param response
     * @param contentType
     * @param contentDisposition
     * @return
     */
    public static boolean FileShowInPage(FTPBean ftpBean, HttpServletResponse response, String contentType, String contentDisposition) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(ftpBean.getHost(), Integer.valueOf(ftpBean.getPort()));
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(ftpBean.getLoginName(), ftpBean.getPassword());// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            //被动模式
//          ftp.enterLocalPassiveMode();
            //主动模式
            ftp.enterLocalActiveMode();
            ftp.changeWorkingDirectory(ftpBean.getStorePath());// 转移到FTP服务器目录
          /*  FTPFile[] fs = ftp.listFiles();
            for (FTPFile ff : fs) {
                if (ff.getName().equals(ftpBean.getFtpFileName())) {*/
                    response.setContentType(contentType);
                    String saveAsFileName = new String(ftpBean.getOriginalFileName().getBytes("UTF-8"), "ISO8859-1");
                    if (StringUtils.trimToNull(contentDisposition) != null)
                        response.setHeader("Content-Disposition", contentDisposition + saveAsFileName);
                        OutputStream os = response.getOutputStream();
                        ftp.setFileType(FTP.BINARY_FILE_TYPE);
                        ftp.retrieveFile(ftpBean.getFtpFileName(), os);
                        os.flush();
                        os.close();
           /*         break;
                }
            }*/
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

        }
        return success;
    }

   /* public static File tanferToFile(MultipartFile file) {
        CommonsMultipartFile cf = (CommonsMultipartFile) file;
        DiskFileItem fi = (DiskFileItem) cf.getFileItem();
        File f = fi.getStoreLocation();
        return f;
    }*/

    public static boolean checkImgByFileName(String fileName) {
        if (fileName.contains(".")) {
            return imgSuffixlist.contains(fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase());
        }
        return false;
    }

    /**
     * 如果目录不存在,则循环创建目录
     *
     * @param ftp
     * @param path ftp服务器文件目录（文件要上传的目录）
     * @return
     * @throws IOException
     */
    public static boolean CreateDirecroty(FTPClient ftp, String path) throws IOException {
        boolean success = true;
        String directory = path.substring(0, path.lastIndexOf("/") + 1);
        logger.debug(directory);
        // 如果远程目录不存在，则循环创建远程服务器目录
        if (!directory.equalsIgnoreCase("/") && !ftp.changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            start = (directory.startsWith("/")) ? 1 : 0;
            end = directory.indexOf("/", start);
            while (true) {
                String subDirectory = new String(path.substring(start, end));
                if (!ftp.changeWorkingDirectory(subDirectory)) {
                    logger.debug(">>>准备创建的目录： " + subDirectory);
                    if (ftp.makeDirectory(subDirectory)) {
                        ftp.changeWorkingDirectory(subDirectory);
                        logger.debug(">>>创建目录成功： " + subDirectory);
                    } else {
                        logger.debug("创建目录失败");
                        success = false;
                        return success;
                    }
                }
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }

    /**
     * 文件删除
     * @param bean
     * @return
     */
    public static boolean deleteFile(FTPBean bean) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        try {
            int reply;
            ftp.connect(bean.getHost(), Integer.valueOf(bean.getPort()));
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(bean.getLoginName(), bean.getPassword());// 登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.enterLocalPassiveMode();
            //ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
            success = ftp.deleteFile(bean.getStorePath()+bean.getFtpFileName());
            ftp.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }

        }
        return success;
    }

    public static boolean checkImgBySuffix(String suffix){
        return imgSuffixlist.contains(suffix);
    }

}